package com.finance.console.service.statisticc;

// 导入你的实体类和DAO（注意entity包路径）
import com.finance.console.entity.IncomeExpense;
import com.finance.console.entity.StatResult;
import com.finance.console.dao.IncomeExpenseDAO;
import com.finance.console.common.Constant;
import com.finance.console.common.FinanceException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

public class FinancialStatService {
    // 初始化DAO（与你的命名一致）
    private final IncomeExpenseDAO recordDAO = new IncomeExpenseDAO();
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

    // 统计方法（修复所有调用错误）
    public StatResult statMonth(int userId, String yearMonth) throws FinanceException {
        try {
            // 1. 解析日期范围（补充完整逻辑）
            Date monthStart = sdf.parse(yearMonth);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(monthStart);
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date monthEnd = calendar.getTime();

            // 2. 调用DAO查询记录（方法名与DAO完全一致）
            List<IncomeExpense> records = recordDAO.findByUserIdAndTime(userId, monthStart, monthEnd);
            if (records.isEmpty()) {
                throw new FinanceException("该月份无收支记录");
            }

            // 3. 统计逻辑（严格使用你的变量名和判断条件）
            BigDecimal totalIncome = BigDecimal.ZERO;
            BigDecimal totalExpense = BigDecimal.ZERO;
            Map<String, BigDecimal> categoryExpense = new HashMap<>();

            for (IncomeExpense record : records) {
                BigDecimal amount = record.getAmount(); // 调用实体类正确的getter
                // 修复方法名大小写（gettype() → getType()）
                if (Constant.INCOME.equals(record.getType())) {
                    totalIncome = totalIncome.add(amount);
                } else if (Constant.EXPENSE.equals(record.getType())) {
                    totalExpense = totalExpense.add(amount.abs());
                    String category = record.getCategory(); // 调用正确的getter
                    categoryExpense.put(
                            category,
                            categoryExpense.getOrDefault(category, BigDecimal.ZERO).add(amount.abs())
                    );
                }
            }

            // 4. 封装结果（与StatResult属性匹配）
            StatResult result = new StatResult();
            result.setPeriod(yearMonth);
            result.setTotalIncome(totalIncome);
            result.setTotalExpense(totalExpense);
            result.setBalance(totalIncome.subtract(totalExpense));
            result.setCategoryExpense(categoryExpense);
            return result;
        } catch (Exception e) {
            throw new FinanceException("统计失败：" + e.getMessage());
        }
    }
}